import json
from fastapi import APIRouter
from app.utils import make_response, ResponseCode
from app.common import logger, mongo_client, JSONEncoder
from app.schemas.novel import Query
from settings import mongo_settings


bp = APIRouter()


@make_response
def novel(body: Query):
    """书籍目录"""
    req_json = body.dict()
    page = req_json['page']
    count = req_json['count']
    q = req_json['q']

    query = {}
    if q:
        if q['name']:
            query['name'] = {'$regex': q['name']}
        if q['author']:
            query['author'] = {'$regex': q['author']}
    result = mongo_client.execute(
        mongo_client.client[mongo_settings.db_novel][mongo_settings.col_novel].find, query
    ).skip((page - 1) * count).limit(count)
    total = result.count()
    data = json.loads(JSONEncoder().encode(list(result)))
    resp_data = {
        'page': page,
        'count': count,
        'total': total,
        'data': data
    }
    return ResponseCode.Success.value, '', resp_data


bp.add_api_route(path='/novel', name='novel', endpoint=novel, methods=['POST'], tags=['书籍目录'])
